import * as React from 'react'
import { Modal, Form, Input, Button, message } from 'antd'
import { ICompany } from '../../types'
import * as api from '../../services/api'

interface Props {
  record?: ICompany
  id: string
  afterClose?: () => void
  onSuccess?: () => void
  getData: () => void
}

export default function Edit(props: Props): JSX.Element {
  const [username, setUsername] = React.useState<string>('')
  const [visible, setVisble] = React.useState<boolean>(true)
  const close = () => {
    setVisble(false)
  }
  return (
    <Modal
      visible={visible}
      title={props.record ? '编辑用户' : '添加用户'}
      onCancel={close}
      maskClosable={false}
      afterClose={props.afterClose}
      destroyOnClose
      footer={[
        <Button type="text" key="cancel" onClick={() => close()}>
          取消
        </Button>,
        <Button type="primary" key="ok" onClick={async () => {
          try {
            const res = await api.addCompanyUser(username, props.id)
            if (res.stat === 'OK') {
              message.success('添加成功')
              props.getData()
              close()
            } else {
              if (res.stat === 'ERR_NOT_FOUND') message.error('用户名不存在')
              if (res.stat === 'ERR_EXISTS') message.error('该用户已属于某公司员工')
            }
          } catch (e) {
            message.error('输入有误')
          }

        }}>
          确认
        </Button>
      ]}
    >
      <Form >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入用户名'
            }
          ]}
        >
          <Input placeholder="请输入长度为6-11的用户名" maxLength={11} minLength={6} onChange={(e) => { setUsername(e.target.value) }} />
        </Form.Item>
      </Form>
    </Modal>
  )
}
